<script setup>
import { ref, onMounted } from 'vue'
import { selectAllW, updateInfo } from '@/api/insertweek' // 引入接口
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const userStore = useUserStore()
const tableData = ref([])

// 状态文本和颜色映射
const statusTextMap = {
  1: '待审批',
  2: '已批准',
  3: '已驳回',
}

const statusColorMap = {
  1: '#E6A23C', // 黄色（待审批）
  2: '#67C23A', // 绿色（已批准）
  3: '#F56C6C', // 红色（已拒绝）
}

const getStatusText = (status) => {
  return statusTextMap[status] || '未知状态'
}

const getStatusColor = (status) => {
  return statusColorMap[status] || '#303133' // 默认黑色
}

// 获取请假记录数据
const fetchLeaveRecords = async () => {
  try {
    console.log(userStore.user.id);
    const res = await selectAllW({
        userId : userStore.user.id
    })
    console.log(res)

    if (res && res.data) {
      tableData.value = res.data.data
    } else {
      tableData.value = []
    }
  } catch (error) {
    console.error('获取请假记录失败:', error)
    tableData.value = []
  }
}

// 审批操作
const handleApprove = async (id) => {
  try {
    await ElMessageBox.confirm('确定审批通过该请假申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    // 调用审批接口
    const res = await updateInfo({
      id: id,
      status: 2, // 更新状态为已批准
    })
    if (res.data.code == "200") {
      // 更新页面数据
      const record = tableData.value.find((item) => item.id === id)
      if (record){
        record.status = 2 // 更新状态为已批准
      }
      ElMessage.success('审批通过！')
    } else {
      ElMessage.error('审批失败，请重试！')
    }
  } catch (error) {
    ElMessage.info('已取消审批')
  }
}

// 驳回操作
// 驳回操作
const handleReject = async (id) => {
  try {
    // 使用 ElMessageBox 并添加输入框
    const reason = await ElMessageBox.prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      inputValue: '', // 默认值为空
      inputValidator: (val) => val.trim().length > 0, // 验证输入是否为空
      inputErrorMessage: '驳回理由不能为空', // 输入为空时的错误信息
    });

    if (reason.action === 'confirm') {
      // 调用驳回接口
      const res = await updateInfo({
        id: id,
        status: 3, // 更新状态为已拒绝
        remark: reason.value, // 将输入的理由传递给后端
        updateBy: userStore.user.id,
      });
      if (res.data.code == "200") {
        // 更新页面数据
        const record = tableData.value.find((item) => item.id === id);
        if (record) {
          record.status = 3; // 更新状态为已拒绝
        }
        ElMessage.success('已驳回！');
      } else {
        ElMessage.error('驳回失败，请重试！');
      }
    }
  } catch (error) {
    ElMessage.info('已取消驳回');
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLeaveRecords()
})
</script>

<template>
  <el-card class="info-card">
    <el-button type="primary" class="info-button">
      我的请假记录
    </el-button>
  </el-card>

  <el-card class="table-card" style="margin-top: 20px;">
    <el-table :data="tableData" style="width: 100%" height="600">
      <!-- 序号 -->
      <el-table-column type="index" label="序号" width="80" align="center" />

      <!-- 名字 -->
      <el-table-column prop="userId" label="工号" width="120" align="center" />

      <!-- 请假类型 -->
      <el-table-column prop="typeDate" label="请假类型" width="120" align="center">
        <template #default="scope">
          <span v-if="scope.row.typeDate === 1" style="color: #67C23A;">
            事假
          </span>
          <span v-else-if="scope.row.typeDate === 2" style="color: #E6A23C;">
            病假
          </span>
          <span v-else-if="scope.row.typeDate === 3" style="color: #409EFF;">
            年假
          </span>
          <span v-else-if="scope.row.typeDate === 4" style="color: #67C23A;">
            婚假
          </span>
          <span v-else-if="scope.row.typeDate === 5" style="color: #E6A23C;">
            产假
          </span>
          <span v-else style="color: #909399;">
            未知类型
          </span>
        </template>
      </el-table-column>

      <!-- 开始时间 -->
      <el-table-column prop="startTime" label="开始时间" width="150" align="center" />

      <!-- 创建时间 -->
      <el-table-column prop="creatTime" label="创建时间" width="150" align="center" />

      <!-- 结束时间 -->
      <el-table-column prop="endTime" label="结束时间" width="150" align="center" />

      <!-- 状态 -->
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <span :style="{ color: getStatusColor(scope.row.status) }">
            {{ getStatusText(scope.row.status) }}
          </span>
        </template>
      </el-table-column>

      <!-- 内容 -->
      <el-table-column prop="content" label="内容" align="center">
        <template #default="scope">
          <div v-html="scope.row.content"></div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 1"
            type="success"
            size="small"
            @click="handleApprove(scope.row.id)"
          >
            审批
          </el-button>
          <el-button
            v-if="scope.row.status === 1"
            type="danger"
            size="small"
            @click="handleReject(scope.row.id)"
          >
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<style scoped>
.info-card {
  height: 70px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
}

.info-button {
  width: 200px;
  font-size: 16px;
  border-radius: 8px;
  text-align: center;
  background: linear-gradient(to right, #4a6bff, #7986cb);
  border: none;
  transition: all 0.3s;
}

.info-button:hover {
  background: linear-gradient(to right, #7986cb, #4a6bff);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.info-button:active {
  transform: translateY(0);
}

.table-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  padding: 20px;
}
</style>